﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ATT.SharePoint.Patterns.BCS;

namespace UMI.Globe.Search.Tests
{
    [TestClass]
    public class CachedConnectorPatternTests
    {
        #region Test methods

        [TestMethod]
        public void ReadItemTest()
        {
            int testIdentifier = 4;
            TestBDCEntity entity = GetServiceInstance().ReadItem(testIdentifier);

            Assert.AreEqual(entity.Identifier, testIdentifier);
            Assert.AreEqual("This is a fake entity with id " + testIdentifier,  entity.TestValue);
        }

        [TestMethod]
        public void ReadListTest()
        {
            IEnumerable<TestBDCEntity> testCache = this.GetServiceInstance().ReadList();
            TestBDCEntity entity = this.GetTestEntity(5);

            Assert.AreEqual(testCache.Count(), 10);
        }

        #endregion

        #region Private methods

        private CachedConnectorService<TestBDCEntity, int> GetServiceInstance()
        {
            CachedConnectorParameters<TestBDCEntity, int> parameters = 
                new CachedConnectorParameters<TestBDCEntity, int>();
            parameters.DatabaseCall = GetDatabaseDelegate();
            parameters.PopulateCache = GetPopulateCacheDelegate();
            parameters.Logger = null;
                
            return new CachedConnectorService<TestBDCEntity, int>(parameters);
        }

        private Func<int, TestBDCEntity> GetDatabaseDelegate()
        {
            return (identifier) =>
            {
                TestBDCEntity entity = new TestBDCEntity();
                entity.Identifier = identifier;
                entity.TestValue = "Fake entity to stub database call.";

                return entity;
            };
        }

        private Action<List<TestBDCEntity>> GetPopulateCacheDelegate()
        {
            return (entities) =>
            {
                int[] fakeListOfIdentifiers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                foreach (int identifier in fakeListOfIdentifiers)
                {
                    entities.Add(this.GetTestEntity(identifier));
                }
            };
        }

        private TestBDCEntity GetTestEntity(int identifier)
        {
            TestBDCEntity entity = new TestBDCEntity();
            entity.Identifier = identifier;
            entity.TestValue = "This is a fake entity with id " + identifier;

            return entity;
        }

        #endregion
    }
}
